// pages/user/user.js
import { Order } from './myOrder-model.js'
const app = getApp()
const order = new Order()
Page({

  /**
   * 页面的初始数据
   */
  data: {
      userInfo: {},
      leftBar: '22',
      nowId:1,
      orderList:null,
      hasMore:false,
      page:1,
      noneData:false,
      threeOrderCount:null,
      allowClick:true,
      soldoutList:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      let userInfo = wx.getStorageSync('userInfo')
      wx.showLoading({
          title: '加载中',
      })
      if (userInfo){
        this.setData({
            userInfo: userInfo,
        })
      }
      this.commonRequest('','','')
  },
//   公共的请求
  commonRequest(orderStatus, logisticStatus,pulldown){
    let { page,userInfo,orderList}  = this.data
    let params = {
        "data":{
            "userId": '' + userInfo.id,
            "orderStatus": orderStatus,
            "logisticStatus": logisticStatus,
            "page": '' + page
        }
    }
    if (orderStatus == '' && logisticStatus == '') {
        delete params.data.orderStatus
        delete params.data.logisticStatus
    }else if (orderStatus == ''){
        delete params.data.orderStatus
    } else if (logisticStatus == ''){
        delete params.data.logisticStatus
    }
    this.commonGetOrderCount()                
    order.getOrder(params,res=>{
        if(res.status){
            wx.hideLoading()
            wx.stopPullDownRefresh()
            res.data.forEach(val=>{
                val.update_time = order.formate(val.update_time)
            })
            if (Math.ceil(res.total / 5) < page ){
                this.setData({
                    hasMore: false,
                    noneData: false,                    
                })
                if (res.total == 0) {
                    this.setData({
                        noneData: true,
                        hasMore: false
                    })
                } 
            }else{
                // 如果orderList存在
                if(orderList){
                    // 如果是下拉
                    if (pulldown == 'pulldown'){
                        orderList = res.data
                    }else{
                        orderList = [...orderList,...res.data]
                    }
                    this.setData({
                        orderList: orderList,
                        hasMore: true,
                        noneData: false
                    })
                    
                }else{  
                    //   如果不存在列表直接添加
                    this.setData({
                        orderList: res.data,
                        hasMore: true,
                        noneData: false                        
                    })
                }
                if (res.total < 3) {
                    this.setData({
                        hasMore: false,
                    })
                }
                // console.log('')
            }
        }else{
            wx.hideLoading()
            order.showMyTip({ _this: this, title: res.data.message })
            wx.stopPullDownRefresh()
        }
    })
  },
//   跳转详情
  jumpDetail(e){
    let { userInfo}=this.data;
    let id=order.getDataSet(e,"id");
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?orderId=' +id + '&storeNo=' + userInfo.storeNo,
    })
  },
//   切换tab
  toggleOrder(e){
    console.log(e.currentTarget.dataset.id)
    var id = e.currentTarget.dataset.id
    wx.showLoading({
        title: '加载中',
    })
    this.setData({
        leftBar: id * 235 - 213,
        nowId: id,
        page: 1,
        hasMore: false,
        orderList: null
    })

    this.commonSwitchReq(+id)
    wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
    })
  }, 
    //   删除订单
  deleteOrder(e){
      var id = e.currentTarget.dataset.id
      let that = this
      wx.showModal({
          title: '提示',
          content: '确认删除该订单吗？',
          success: function (res) {
              if (res.confirm) {
                  console.log('用户点击确定')
                  let params = {
                      "data":{
                          "orderId": "" + id
                      }
                  }
                  wx.showLoading({
                      title: '加载中',
                  })
                  order.deleteOrder(params,res=>{
                      if(res.status){
                          wx.hideLoading()
                          wx.showToast({
                              title: '删除成功',
                              icon: 'success',
                              duration: 2000,
                              success() {
                                  setTimeout(() => {
                                    that.onPullDownRefresh()
                                  },1500)
                              }
                          })
                      }
                  })

              } else if (res.cancel) {
                  console.log('用户点击取消')
              }
          }
      })
  },  
  trace(e){
      var id = e.currentTarget.dataset.id      
      var addressId = e.currentTarget.dataset.address      
      wx.navigateTo({
          url: '/pages/orderTrace/orderTrace?addressId=' + addressId +'&orderId='+ id
      })
  },
  //立即支付
  pay(e){
      let that = this
      var dataset = e.currentTarget.dataset
      var id = dataset.id
      var addressId = dataset.address
      let orderList = this.data.orderList
      let allowClick = this.data.allowClick
      console.log(id, addressId)
      let wxuid = wx.getStorageSync('wxUid');
      let params = {
          data:{
            "wxuid": wxuid,
            "orderId": id
          }
      }
      console.log(params)
      this.setData({
          allowClick:false
      })
      wx.showLoading({
          title: '加载中',
      })
        //   查询订单地址是否有效
      order.getUserAddressById({
          "data":{
              id: ''+addressId
          }
      },res=>{
          if(res.status){
                if (!allowClick) {console.log('多点拦截'); return}
                //   如果地址关联了并且状态不是删除的状态就可以发起支付
                if(addressId && res.data.status != 1){
                    order.wxPay(params, res => {
                        wx.hideLoading()                        
                        if (res.status) {
                        let data = res.data
                        console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign, data.stockList)
                            if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS") {
                                
                                console.log('success')
                                wx.requestPayment({
                                    'timeStamp': '' + data.miniTimeStamp,
                                    'nonceStr': '' + data.miniNonceStr,
                                    'package': 'prepay_id=' + data.prepay_id,
                                    'signType': 'MD5',
                                    'paySign': '' + data.miniPaySign,
                                    'success': function (result) {
                                        console.log('pay', result)
                                        order.reduceGoodsStock({
                                            "data":{
                                                orderId: id
                                            }
                                        },reduce=>{
                                            orderList.forEach((val,i)=>{
                                                if(val.id == id){
                                                    let orderList = 'orderList[' + i +'].order_status'              
                                                    that.setData({
                                                        [orderList]:'S',
                                                        allowClick: true
                                                    })
                                                }
                                            })
                                        })
                                    },
                                    'fail': function (result) {
                                        that.setData({
                                            allowClick: true
                                        })
                                    }
                                })
                            } else if (data.stockList && data.stockList.length > 0) {
                                console.log(data.stockList)
                                this.setData({
                                    soldoutList: data.stockList,
                                    allowClick: true
                                })
                            }
                        } else{
                            this.setData({
                                allowClick: true
                            })
                        }
                    })
                }else{
                    let { userInfo } = this.data;
                    wx.hideLoading()                                            
                    console.log('无地址关联')
                    wx.navigateTo({
                        url: '/pages/orderDetail/orderDetail?orderId=' + id + '&storeNo=' + userInfo.storeNo,
                    })
                    this.setData({
                        allowClick: true
                    })
                }

          }else{
              wx.hideLoading()                                                         
              order.showMyTip({ _this: this, title:'服务器错误' })              
          }
      })
  },
  soldoutBack(){
    this.setData({
        soldoutList:null,
        allowClick: true
        
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      var { page, hasMore, nowId } = this.data;
      console.log('bottom', nowId)
      /**
       * 此处加上数据大小的判断
       */
      nowId = +nowId
        this.setData({
            page: 1,
            allowClick:true
        })
        this.commonSwitchReq(nowId,'pulldown')
  },
  showAddAddress(){
    this.setData({
        dialogShow: true
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
      var { nowId } = this.data; 
      this.setData({
          page:1,
      })     
      
      this.commonSwitchReq(+nowId,'pulldown')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
      var { page, hasMore, nowId } = this.data;
      console.log('bottom', nowId)
      /**
       * 此处加上数据大小的判断
       */
      nowId = +nowId
      if (hasMore) {
          this.setData({
              page: page + 1
          })
          this.commonSwitchReq(nowId)
      }
  },
    // 封装tab的不同请求
    commonSwitchReq(id,pulldowm){
        switch (id) {
            case 1:
                this.commonRequest('', '', pulldowm)
                break;
            case 2:
                this.commonRequest('W', '', pulldowm)
                break;
            case 3:
                this.commonRequest('S', 'LW', pulldowm)
                break;
        }
    },
    commonGetOrderCount(){
        let parmas = {
            "data":{
                "userId": ''+this.data.userInfo.id
            }
        }
        order.getOrderCount(parmas,res=>{
            if(res.status){
                this.setData({
                    threeOrderCount:res.data
                })
                
            }else{
                wx.hideLoading()
                order.showMyTip({ _this: this, title: '服务器错误' })
                wx.stopPullDownRefresh()
            }
        })
    },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})